<template>
  <!-- 要货表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="700px"
      draggable
      @close="closeDialog"
      :close-on-click-modal="false"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        v-loading="loading1"
        :rules="rules"
        label-width="90px"
        style="display: flex"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编号">
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称">
              <el-input
                v-model="formData.materialName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="计划日期">
              <el-input
                v-model="formData.requireDate"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="planQuantity">
              <el-radio-group v-model="radio" @change="radioChange">
                <el-radio :label="1" size="large">计划数量</el-radio>
                <el-radio :label="2" size="large">炉 数</el-radio>
              </el-radio-group>
            </el-form-item>

            <!--<el-form-item label="计划数量" prop="planQuantity">
              <el-input
                v-model="formData.planQuantity"
                placeholder="请输入计划数量"
                style="width: 100%"
              />
            </el-form-item>-->
          </el-col>
          <el-col :span="24">
            <el-form-item label="数量/炉数" prop="planQuantity">
              <el-input
                v-model="formData.planQuantity"
                placeholder="请输入计划数量"
                style="width: 100%"
              />
            </el-form-item>
            <!--<el-form-item label="炉数" prop="stoveCount">
              <el-input
                v-model="formData.stoveCount"
                placeholder="请输入计划炉数"
                style="width: 100%"
              />
            </el-form-item>-->
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer" v-if="!loading1">
          <el-button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <!--(props.title == '反馈信息' && props.hhStatus==null)||props.demandStatus == 2"  -->
          <el-button
            v-if="props.demandStatus == 2"
            type="danger"
            :loading="loadingReject"
            @click="reject(props.cellId)"
            >驳 回</el-button
          >
          <el-button
            v-if="props.demandStatus == 3 && props.title == '确认信息'"
            type="danger"
            :loading="loadingRevoke"
            @click="revoke(props.cellId)"
            >撤 销</el-button
          >
          <el-button
            v-if="props.demandStatus == 3 && props.title == '确认信息'"
            type="primary"
            :loading="loadingAllow"
            @click="allown(props.cellId)"
            >允许发货</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { mockTableDetail } from "../utilejs/mock";
import dayjs from "dayjs";

const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "PLANFEEDBACKINFODIALOG",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  cellId: {
    type: String,
    default: () => {
      return "";
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  begirate: {
    type: String,
    default: () => {
      return "";
    },
  },
  endDate: {
    type: String,
    default: () => {
      return "";
    },
  },
  demandStatus: {
    type: Number,
    default: () => {
      return 0;
    },
  },
  hhStatus: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const disabled = ref(false);
const loading1 = ref(false);
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (props.cellId) {
      Object.assign(formData, props.data);
    }
  }
);
const validateQuantity = (rule, value) => {
  if (formData.planQuantity > 0 && formData.stoveCount > 0) {
    return Promise.reject("炉数与模数只能填写一个！");
  }
  return Promise.resolve();
};
// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  demandDate: [
    {
      required: true,
      message: "未选择要货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "blur" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [
    {
      validator: planQuantity,
      trigger: "blur",
    },
    {
      validator: validateQuantity,
      trigger: "blur",
    },
  ],
  stoveCount: [
    {
      validator: planQuantity,
      trigger: "blur",
    },
    {
      validator: validateQuantity,
      trigger: "blur",
    },
  ],
  dischargeHatchId: [
    { required: true, message: "未选择卸货口", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  planId: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  requireDate: "",
  planQuantity: "",
  planQuantitySum: 0,
  thisMonthOrderQuantity: 0,
  pm: 0,
  mfurnace: 0,
  stoveCount: 0,
  lastMonthScrapRate: 0,
});

// 获取反馈信息
const getCellList = async (id) => {
  await request({
    url: `/srm/srmdemandfeedback/getInfo/${id}`,
    method: "get",
  })
    .then((res) => {
      Object.assign(formData, { ...res.data });
      loading1.value = false;
    })
    .catch(() => {
      Object.assign(formData, { ...mockTableDetail });
      loading1.value = false;
    });
};
// 获取确认数量一行单元格信息
const getOkCellList = async (id) => {
  await request({
    url: `/srm/srmdemandschedule/getConfirmQuantityCellInfo/${id}`,
    method: "get",
  }).then((res) => {
    Object.assign(formData, { ...res.data });
    loading1.value = false;
  });
};
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formData.id = "";
  formData.planId = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.requireDate = "";
  formData.planQuantity = "";
  formData.planQuantitySum = 0;
  formData.thisMonthOrderQuantity = 0;
  formData.pm = 0;
  formData.mfurnace = 0;
  formData.stoveCount = 0;
  formData.lastMonthScrapRate = 0;
  radio.value = 1;
}

const loading = ref(false);

// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  return !(
    time.getTime() <= dayjs(props.endDate) &&
    time.getTime() >= dayjs(props.begirate)
  );
};

/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (
        radio.value == 1 ? (formData.planQuantitySum + Number(formData.planQuantity) * (1 - (formData.lastMonthScrapRate * 0.01)) * formData.pm <
        formData.thisMonthOrderQuantity) :
        (formData.planQuantitySum + (Number(formData.planQuantity) * formData.mfurnace) * (1 - (formData.lastMonthScrapRate * 0.01)) * formData.pm <
        formData.thisMonthOrderQuantity)
      ) {
        ElMessageBox.confirm(
          "计划总数量不满足当月订单数量，是否确认修改?",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(async () => {
          loading.value = true;
          if (radio.value == 2) {
            formData.planQuantity = Number(formData.planQuantity) * formData.mfurnace;
          }
          const text = formData.id ? "编辑" : "新增";
          await request({
            url: "/mes/mesplanmonthplanactual/save",
            method: "post",
            data: formData,
          }).finally(() => {
            loading.value = false;
            formData.stoveCount = 0;
          });
          ElMessage.success(text + `成功`);
          closeDialog();
          emit("reset-table", formData.id);
        });
        return;
      }
      if (radio.value == 2) {
        formData.planQuantity = Number(formData.planQuantity) * formData.mfurnace;
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesplanmonthplanactual/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
        formData.stoveCount = 0;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 驳回按钮
const loadingReject = ref(false);
async function reject(id: any) {
  ElMessageBox.confirm("确认驳回该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingReject.value = true;
    await request({
      url: `/srm/srmdemandschedule/reject/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("驳回成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingReject.value = false;
      });
  });
}
// 撤销按钮
const loadingRevoke = ref(false);
async function revoke(id: any) {
  ElMessageBox.confirm("确认撤销该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingRevoke.value = true;
    await request({
      url: `/srm/srmdemandschedule/revoke/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("撤销成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingRevoke.value = false;
      });
  });
}
// 允许发货按钮
const loadingAllow = ref(false);
async function allown(id: any) {
  ElMessageBox.confirm("确认允许发货吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingAllow.value = true;
    await request({
      url: `/srm/srmdemandfeedback/allowShipment/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("发货成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingAllow.value = false;
      });
  });
}
onMounted(() => {});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
function validateNumber(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) <= 0) {
    callback(new Error("请输入大于0的值"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else {
    callback();
  }
}
function planQuantity(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else {
    callback();
  }
}
const radio = ref(1);
function radioChange() {
  console.log(radio.value);
  // if (radio.value == 1) {
  //   formData.planQuantity = formData.mfurnace;
  // }
  if (radio.value == 2) {
    formData.planQuantity = 1;
  }
}
</script>

<style lang="scss" scoped>
.formTable {
  :deep(.el-scrollbar__wrap) {
    max-height: 200px;
    overflow-y: auto;
  }
}
</style>
